package com.sangeng.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sangeng.domain.ResponseResult;
import com.sangeng.domain.constants.SystemConstants;
import com.sangeng.domain.dto.ArticleDto;
import com.sangeng.domain.entity.Article;
import com.sangeng.domain.entity.ArticleTag;
import com.sangeng.domain.entity.Category;
import com.sangeng.domain.entity.Tag;
import com.sangeng.domain.vo.ArticleDetailVo;
import com.sangeng.domain.vo.ArticleVo;
import com.sangeng.domain.vo.HotArticleVo;
import com.sangeng.domain.vo.PageVo;
import com.sangeng.mapper.ArticleMapper;
import com.sangeng.service.ArticleService;
import com.sangeng.service.ArticleTagService;
import com.sangeng.utils.BeanCopyUtils;
import com.sangeng.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Queue;
import java.util.stream.Collectors;

/**
 * ClassName: ArticleServiceImpl
 * Package: com.sangeng.service.impl
 * Description:
 *
 * @Author hjh
 * @Create 2024/8/11 14:31
 * @Version 1.0
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Autowired
    private  CategoryServiceImpl categoryService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ArticleTagService articleTagService;
    @Override
    public ResponseResult hotArticlList() {
        //查询热门文章 封装成ResponseResult返回
        LambdaQueryWrapper<Article> wrapper=new LambdaQueryWrapper<>();
        //必须是正式文章
        wrapper.eq(Article::getStatus, SystemConstants.STATUS_NORMAL);
        //按照浏览量进行排序
        wrapper.orderByDesc(Article::getViewCount);
        //最多只查询10条
        Page<Article> page=new Page<>(1,10);
        page(page,wrapper);

        List<Article> articles = page.getRecords();

        //bean拷贝
        List<HotArticleVo> hotArticleVos= BeanCopyUtils.copyBeanList(articles, HotArticleVo.class);
        return ResponseResult.okResult(hotArticleVos);
    }

    @Override
    public ResponseResult articleList(Integer pageNumber, Integer pageSize, Long categoryId) {
        //查询条件
        LambdaQueryWrapper<Article> queryWrapper=new LambdaQueryWrapper();
        //查看是否有分类id如果有加入到查询条件
        queryWrapper.eq(Objects.nonNull(categoryId)&&categoryId>0,Article::getCategoryId,categoryId);
        // 状态是正式发布的
        queryWrapper.eq(Article::getStatus,SystemConstants.STATUS_NORMAL);
        // 对isTop进行降序
        queryWrapper.orderByDesc(Article::getIsTop);

        //分页查询
        Page<Article> page=new Page<>();
        page(page,queryWrapper);

        List<Article> articles=page.getRecords();
        //查询categoryName
//        articles.stream()
//                .map(article -> article.setCategoryName(categoryService.getById(article.getCategoryId()).getName()))
//                .collect(Collectors.toList());
        for (Article article : articles) {
            Category category = categoryService.getById(article.getCategoryId());
            article.setCategoryName(category.getName());
        }
        //封装查询结果
        List<ArticleVo> articleVos = BeanCopyUtils.copyBeanList(page.getRecords(), ArticleVo.class);

        PageVo pageVo = new PageVo(articleVos,page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult getArticleDetail(Long id) {

        Article article =getById(id);
        //从redis中获取viewCount
        Integer viewCount = redisCache.getCacheMapValue("article:viewCount", id.toString());
        article.setViewCount(viewCount.longValue());
        ArticleDetailVo articleDetailVo = BeanCopyUtils.copyBean(article, ArticleDetailVo.class);
        //根据分类id查询分类名
        Long categoryId = articleDetailVo.getCategoryId();
        Category category = categoryService.getById(categoryId);
        if(category!=null){
            articleDetailVo.setCategoryName(category.getName());
        }

        return ResponseResult.okResult(articleDetailVo);
    }

    @Override
    public ResponseResult updateViewCount(Long id) {
        //更新redis中对应 id的浏览量
        redisCache.incrementCacheMapValue("article:viewCount",id.toString(),1);
        return ResponseResult.okResult();
    }

    @Override
    @Transactional
    public ResponseResult addArticle(ArticleDto articleDto) {
        //先将博文插入后获取插入的id才能进行后续操作
        Article article = BeanCopyUtils.copyBean(articleDto, Article.class);
        save(article);
        //根据tags生成文章与文章相关的 article_tag表
        List<Long> tags = articleDto.getTags();
        List<ArticleTag> articleTagList=new ArrayList<>();
        for (Long tag : tags) {
            ArticleTag at=new ArticleTag();
            at.setArticleId(article.getId());
            at.setTagId(tag);
        }
        //批量插入
        articleTagService.saveBatch(articleTagList);

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getPageList(Long pageNum, Long pageSize, String title, String summary) {
        //封装查询条件
        LambdaQueryWrapper<Article> queryWrapper=new LambdaQueryWrapper<>();
        //不能把删除了的文章查询出来（已经在配置文件中实现）
        queryWrapper
                //设置模糊查询条件
                .like(StringUtils.hasText(title),Article::getTitle,title)
                .like(StringUtils.hasText(summary), Article::getSummary,summary);

        Page<Article> articlePage=new Page<>();
        page(articlePage,queryWrapper);
        PageVo pageVo=new PageVo(articlePage.getRecords(),articlePage.getTotal());

        return ResponseResult.okResult(pageVo);
    }


    @Override
    public ResponseResult getArticleById(Long id) {
        //根据id查询文章
        Article article = getById(id);
        //根据文章id查询所关联的tags
        LambdaQueryWrapper<ArticleTag> articleTagLQW=new LambdaQueryWrapper<>();
        articleTagLQW.eq(ArticleTag::getArticleId,id);
        List<ArticleTag> list = articleTagService.list(articleTagLQW);

        List<Long> tags = list.stream().map(ArticleTag::getTagId).collect(Collectors.toList());
        //类型转换
        ArticleDto articleDto = BeanCopyUtils.copyBean(article, ArticleDto.class);
        articleDto.setTags(tags);
        return ResponseResult.okResult(articleDto);
    }

    @Override
    @Transactional
    public ResponseResult updateArticle(ArticleDto articleDto) {
        //首先更具文章id删除文章和tags关联表中的数据
        LambdaQueryWrapper<ArticleTag> articleTagLQW=new LambdaQueryWrapper<>();
        articleTagLQW.eq(ArticleTag::getArticleId ,articleDto.getId());
        articleTagService.remove(articleTagLQW);
        //重新添加tagId
        List<ArticleTag> articleTags = articleDto.getTags().stream()
                .map(aLong -> new ArticleTag(articleDto.getId(),aLong))
                .collect(Collectors.toList());

        articleTagService.saveBatch(articleTags);
        //将dto转换为正常实体类后进行存储
        Article article = BeanCopyUtils.copyBean(articleDto, Article.class);
        updateById(article);
        return ResponseResult.okResult();
    }

    @Override
    @Transactional
    public ResponseResult deleteArticleById(Long articleId) {
        //将和这个关联的tags删除
        LambdaQueryWrapper<ArticleTag> articleTagLQW=new LambdaQueryWrapper<>();
        articleTagLQW.eq(ArticleTag::getArticleId ,articleId);
        articleTagService.remove(articleTagLQW);
        //TODO 删除和文章相关联的评论
        //在将文章逻辑删除
        removeById(articleId);
        return ResponseResult.okResult();
    }
}
